package deviceSyc;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public abstract class MQCon {
	protected Channel channel;
    protected Connection connection;
    protected String endPointName;
    protected String exchangeName;
    protected String queueName;
    protected String routingKey;
    protected String bindingKey;
    String rootPath = System.getProperty("user.dir").replace("\\", "/");
     
    public MQCon() throws IOException{
         
         //load configure file
         Properties pps = new Properties();
         pps.load(new FileInputStream(rootPath + "/res/configure.properties"));
         this.exchangeName = pps.getProperty("exchangeName");
         this.queueName = pps.getProperty("queueName");
         this.routingKey = pps.getProperty("senderServiceName");
         this.bindingKey = pps.getProperty("receiverServiceName");
         //Create a connection factory
         ConnectionFactory factory = new ConnectionFactory();
         //hostname of your rabbitmq server
         factory.setHost(pps.getProperty("rabbitHost"));
         factory.setAutomaticRecoveryEnabled(true);
//         factory.setUsername("jlpostadmin");
//         factory.setPassword("123456");
         //getting a connection
         try {
			connection = factory.newConnection();
			// 关键所在，指定线程池  
			ExecutorService service = Executors.newFixedThreadPool(500);  
			factory.setSharedExecutor(service);
			factory.setAutomaticRecoveryEnabled(true);
		} catch (TimeoutException e) {
			e.printStackTrace();
		}
         //creating a channel
         channel = connection.createChannel();
         channel.queueDeclarePassive(queueName);
//         channel.queueDeclare(queueName, true, false, false, null);
         channel.exchangeDeclarePassive(exchangeName);
//         channel.exchangeDeclare(exchangeName, "direct"/*exchange类型为direct*/);
         //declaring a queue for this channel. If queue does not exist,
         //it will be created on the server.
//         channel.queueDeclare("testquene", false, false, false, null);
    }
     
     
    /**
     * 关闭channel和connection。并非必须，因为隐含是自动调用的。
     * @throws IOException
     */
     public void close() throws IOException{
         try {
			this.channel.close();
		} catch (TimeoutException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
         this.connection.close();
     }
}
